package com.honey.mamabike.security;

import org.omg.CORBA.PRIVATE_MEMBER;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * Created by setsun on 2017/10/10.
 */
public class RSAUtil {

    private static final String KEY_ALGORITHM = "RSA";
    //gongyue
    private static String PUBLIC_KEY="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC3ISQsoVifuZHPyya1Cy61 snTR2h14EeRDnq3iM4Sq1ppdtT3sz6g+LcjW1ZTFn6t8OU1Epl2GTPlC+3qR Y/aytkMYsmIXdF7yHr9B1CgzYCaU73XM2Lb4A+ebLxhZQ1/BP48yIuCPJ6rG E74hpUQjp9H64SeMCblDcA/wmJBEqwIDAQAB";

    //siyue
    private static String PRIVATE_KEY="";

    /**
     * 读取私钥
     * @throws Exception
     */
    public static void convert() throws Exception {
        byte[] data = null;
        try {
            InputStream is = RSAUtil.class.getResourceAsStream("/enc_pri");
            int len = is.available();   //一次读完
            data = new byte[len];
            is.read(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String dataStr = new String(data);
        try{
            PRIVATE_KEY = dataStr;
        }catch (Exception e){

        }

        if (PRIVATE_KEY == null){
            throw new Exception("Fail to retrieve key");
        }

    }

    /**
     * 加密非对称算法
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPublicKey(byte[] data,String key) throws Exception {
        byte[] keyBytes = Base64Util.decode(key);
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicKey =  keyFactory.generatePublic(x509EncodedKeySpec);

        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(data);
    }


    /**
     * 解密算法
     * @param data
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey(byte[] data) throws Exception {
        convert();

        byte[] keyBytes = Base64Util.decode(PRIVATE_KEY);

        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        return cipher.doFinal(data);
    }






    public static void main(String[] args) throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        System.out.println(Base64Util.encode(publicKey.getEncoded()));  //gongyue
        System.out.println();
        System.out.println(Base64Util.encode(privateKey.getEncoded()));
       String data ="老李来了..";
       byte[] enResult = encryptByPublicKey(data.getBytes("UTF-8"),PUBLIC_KEY);
        System.out.println(enResult+"11111");

        byte[] deResult = decryptByPrivateKey(enResult);
        System.out.println(new String(deResult, "UTF-8"));

    }
}
